<?php

namespace App\Http\Controllers\Admin;

use App\Models\Course;
use App\Models\Dict;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class DictController extends Controller
{
    //
    public function index(Request $request)
    {
        $limit = $request->get('limit', 10);
        $model = Dict::query();
        $model = $model->with(['children' => function ($q) {
            $q->orderBy('sort', 'asc');
        }]);
        $model = $model->where('did', 0);
        $result = $model->orderBy('sort', 'asc')->orderBy('id', 'desc')->paginate($limit);
        return showMsg('操作成功', 200, $result);
    }

    public function getDict(Request $request)
    {
        $dictname = $request->get('dictname');
        $array = Dict::select('id', 'dkey', 'dvalue', 'dicon')->where(['dictname' => $dictname, 'status' => 1])->where('did', '!=', 0)->orderBy('sort', 'asc')->get();
        return showMsg('获取成功', 200, $array);
    }

    public function detail(Request $request)
    {
        $id = $request->get('id');
        $result = Dict::findOrFail($id);
        if (!$result) {
            return showMsg('信息已删除', 201, $result);
        }
        return showMsg('操作成功', 200, $result);
    }

    public function beforeSave(Request $request)
    {
        $id = $request->get('id');
        $data = $request->all();
        if ($id) {
            $article = Dict::findOrFail($id);
            if ($article->update($data)) {
                return showMsg('更新成功', 200);
            }
        } else {
            Dict::create($data);
            return showMsg('添加成功', 200);
        }
    }

    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (empty($ids)) {
            return showMsg('请选择操作项', 201);
        }
        if (is_array($ids)) {
            foreach ($ids as $v) {
                Dict::destroy('id', $v);
            }
        } else {
            Dict::destroy('id', $ids);
        }
        return showMsg('删除成功', 200);
    }

}
